package handlers

import (
	"log"

	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs/postservice"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/title_service/titleservice"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/user/userservice"

	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/transport"
	"github.com/gin-gonic/gin"
	consul "github.com/kitex-contrib/registry-consul"
)

var UserClient userservice.Client
var PostClient postservice.Client
var TitleClient titleservice.Client

func init() {
	var err error

	// 创建consul注册中心解析器
	r, err := consul.NewConsulResolver("192.168.17.135:8500")
	if err != nil {
		log.Fatalf("Failed to create consul resolver: %v", err)
	}

	// 初始化PostService客户端
	PostClient, err = postservice.NewClient("post-rpc",
		client.WithResolver(r),
	)
	if err != nil {
		log.Fatalf("Failed to create PostService client: %v", err)
	}

	// 初始化UserService客户端
	UserClient, err = userservice.NewClient("user-rpc",
		client.WithResolver(r),
	)
	if err != nil {
		log.Fatalf("Failed to create UserService client: %v", err)
	}

	// 初始化TitleService客户端
	TitleClient, err = titleservice.NewClient("title-service-grpc",
		client.WithResolver(r),
		client.WithTransportProtocol(transport.GRPC))
	if err != nil {
		log.Fatalf("Failed to create TitleService client: %v", err)
	}
}

// SetupRoutes 设置所有路由
func SetupRoutes(router *gin.Engine) {

	// 健康检查端点
	router.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status":  "ok",
			"service": "gateway-service",
		})
	})

	// 用户相关路由
	userGroup := router.Group("/api/users")
	{
		userGroup.GET("/:userId/posts", GetUserPosts)
		userGroup.GET("/:userId", GetUser)
		userGroup.GET("/:userId/following", GetUserFollowing)
		userGroup.POST("/:userId/follow", FollowUser)
	}

	// 帖子相关路由
	postGroup := router.Group("/api/posts")
	{
		postGroup.GET("", GetPosts)
		postGroup.GET("/:postId", GetPostDetail)
		postGroup.POST("/:postId/like", LikePost)
		postGroup.DELETE("/:postId/like", CancelLikePost)
		postGroup.POST("/:postId/save", SavePost)
		postGroup.DELETE("/:postId/save", CancelSavePost)
		postGroup.POST("", CreatePost)
		postGroup.PUT("/:postId", UpdatePost)
		postGroup.DELETE("/:postId", DeletePost)
		postGroup.POST("/recommend_title", GetRecommendTitle)
	}
}
